package cn.sofwin.web.blog.servlet;

import cn.sofwin.web.blog.entity.User;
import cn.sofwin.web.blog.service.UserService;
import cn.sofwin.web.blog.service.impl.UserServiceImpl;
import cn.sofwin.web.blog.utils.FileHelper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 用户资料Servlet
 * @author ZX
 * @version 1.0
 */
@WebServlet("/blog/user/profile")
public class UserProfileServlet extends HttpServlet {

    /** 文件上传的路径（相对于站点根目录） */
    private String uploadPath = "/static/upload/";

    /** 用户服务接口 */
    private UserService userService = UserServiceImpl.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // Session中的用户信息一般比较少，我们需要查询完整信息
        User user = (User) req.getSession().getAttribute("LOGIN_USER");
        User currentUser = userService.get( user.getId() );

        req.setAttribute("user", currentUser);
        // 跳转到个人资料修改页面
        req.getRequestDispatcher("/profile.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 磁盘文件工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 配置文件上传目录
        String folderPath = FileHelper.getWebRootPath(this.getClass()) + uploadPath;
        File uploadFolder = new File(folderPath);
        factory.setRepository(uploadFolder);
        ServletFileUpload upload = new ServletFileUpload(factory);

        String nickname = null;
        String password = null;
        String avatar = null;

        try {
            List<FileItem> items = upload.parseRequest(req);
            for(FileItem item: items){
                if(item.isFormField()){
                    // 处理普通的表单元素
                    String name = item.getFieldName();
                    String value = item.getString("UTF-8");

                    switch (name){
                        case "nickname":
                            nickname = value;
                            break;
                        case "password":
                            password = value;
                            break;
                    }
                } else {
                    // 处理文件上传
                    // 为了防止文件重名，需要重新设置文件名
                    String fileName = item.getName(); // a1.jpg
                    fileName = fileName.substring(fileName.lastIndexOf("."));
                    fileName = System.currentTimeMillis() + fileName;

                    // 存储文件
                    item.write(new File(folderPath + fileName ));

                    // 设置头像访问路径
                    avatar = uploadPath + fileName;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


        User user = (User) req.getSession().getAttribute("LOGIN_USER");

        // 更新用户资料
        userService.updateProfile(user, password, nickname, avatar);

        // 用户可能修改了密码，要求重新登录
        // 1. 移除Session中的用户对象
        req.getSession().removeAttribute("LOGIN_USER");

        // 2. 重定向到登录页面
        resp.sendRedirect("/blog/user/login");

    }
    

}